package com.xuan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuan.base.constant.MQConstant;
import com.xuan.base.constant.RedisConstant;
import com.xuan.mapper.AuthResourceMapper;
import com.xuan.oath.client.api.model.entity.Resource;
import com.xuan.service.AuthResourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Lenovo
 * @description: TODO
 * @date 2021/7/26 10:24
 */
@Service
@Slf4j
public class AuthResourceServiceImpl extends ServiceImpl<AuthResourceMapper, Resource> implements AuthResourceService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @RabbitListener(queues = {MQConstant.ADD_REDIS_RESOURCE_QUEUE})
    public void addRedisResource(@Payload Integer flag){
        if (flag.equals(1)){
            List<Resource> resources = this.list();
            Map<String,List<String>> redisMap = new TreeMap<>();
            resources.forEach(resource -> redisMap.put(resource.getUrl(), Arrays.asList(resource.getRole().split(","))));
            redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_ROLES_MAP,redisMap);

            log.info("存入缓存中数据===={}",redisTemplate.opsForHash().keys(RedisConstant.RESOURCE_ROLES_MAP));
        }
    }
}
